<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>商品介绍</h3>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="goods.productName" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="goods.price" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="productTypeId">
          <el-select v-model="goods.productTypeId" placeholder="请选择商品分类">
            <el-option v-for="(item, index) in categoryList" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload ref="uploadRef" action="#" :limit="1" list-type="picture-card" class="avatar-uploader"
            :class="{ isFileHide: goods.pic }" accept=".jpg,.jpeg,.png" :on-preview="handlePreview"
            :on-remove="handleRemove" :http-request="handleUpload" :before-upload="beforeUpload">
            <i slot="default" class="el-icon-plus" />

            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in" />
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>

          </el-upload>

        </el-form-item>
        <el-form-item label="商品详细介绍">
          <editor v-model="goods.description" :init="editorInit" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish('goods')">发布</el-button>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { publishGoods } from '@/api/goods'
import { listCategory } from '@/api/category'
import { uploadFileUnParam } from '@/api/file'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'

export default {
  name: 'GoodsCreate',
  components: { Editor },

  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      categoryList: [],
      fileList: [],
      goods: { productName: '', price: '', productTypeId: '', description: '', picUrl: '', pic: '' },
      rules: {
        productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }, { validator: this.validateTrueNum }],
        productTypeId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        pic: [{ required: true, message: '请上传商品图片', trigger: 'change' }]

      },
      editorInit: {
        language: 'zh_CN',
        height: '350px',
        convert_urls: false,
        plugins: [
          'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ],
        images_upload_handler(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          uploadFileUnParam(formData)
            .then(res => {
              success(res.data.fileUrl)
            })
            .catch(() => {
              failure('上传失败，请重新上传')
            })
        }
      }
    }
  },
  created() {
    this.getCateGoryList()
  },

  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.goods.pic = ''
      this.$refs.uploadRef.clearFiles()
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 选择文件确认上传
    beforeUpload(file) {
      const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      const allowFileType = ['jpg', 'png', 'jpeg']
      if (allowFileType.indexOf(fileType) === -1) {
        this.$message.error('附件仅支持jpg/png/jpeg格式')
        return false
      }
      const limit = file.size / 1024 / 1024 < 2
      if (!limit) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }

      return limit
    },
    // 获取所属分类
    getCateGoryList() {
      const params = {
        shopId: Cookies.get('shopId')
      }
      listCategory(params).then((res) => {
        if (res.code === 200) {
          console.log('res.data', res.data)
          const result = res.data
          this.categoryList = result.map(item => {
            return {
              label: item.productTypeName,
              value: item.productTypeId
            }
          })
        }
      })
    },
    // 文件上传接口
    handleUpload(file) {
      // this.goods.pic = '111'
      const fromData = new FormData()
      fromData.append('file', file.file)
      uploadFileUnParam(fromData).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.goods.pic = res.data.fileUrl
          // this.fileList.push({ name: '', url: res.data.fileUrl })
          this.$notify.success('图片上传成功')
        } else {
          this.goods.pic = ''
        }
      }).catch(err => {
        console.log(err)
        this.goods.pic = ''
      })
    },
    handleCancel() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: '/goods/list' })
    },
    handlePublish(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = { ...this.goods }
          params.shopId = Cookies.get('shopId')
          publishGoods(params).then(response => {
            this.$notify.success({
              title: '成功',
              message: '创建成功'
            })
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push({ path: '/goods/list' })
          }).catch(response => {
            MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
              confirmButtonText: '确定',
              type: 'error'
            })
          })
        }
        else {
          return;
        }
      })

    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1)
      this.goods.keywords = this.keywords.toString()
    },
    uploadPicUrl(response) {
      console.log('res', response)
      this.goods.picUrl = response.data.fileUrl
    },
    uploadOverrun: function () {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.goods.gallery.push(response.data.url)
      }
    }
    // handleRemove: function (file, fileList) {
    //   for (var i = 0; i < this.goods.gallery.length; i++) {
    //     // 这里存在两种情况
    //     // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
    //     //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
    //     // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
    //     var url
    //     if (file.response === undefined) {
    //       url = file.url
    //     } else {
    //       url = file.response.data.url
    //     }
    //
    //     if (this.goods.gallery[i] === url) {
    //       this.goods.gallery.splice(i, 1)
    //     }
    //   }
    // },
  }
}
</script>
<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.op-container {
  display: flex;
  justify-content: center;
}

.isFileHide .el-upload--picture-card {
  display: none !important;
}

.isFileHide div {
  width: 100%;
  height: 100%;
}
</style>
